﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Car_Rental;
using System.Data.Linq;
using System.Reflection;
using System.Data.SqlClient;
namespace Entity
{
    public static class CreatDataTable
    {
        private static string dbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Car_Rental"].ConnectionString;

        public static void CheckDataTableIsExists()
        {
            LinqCar_RentalDataContext db = new LinqCar_RentalDataContext(dbConnectionString);
            if (db.DatabaseExists() == false)
            {
                db.CreateDatabase();
            }

            CreateTables();
        }

  
        /// <summary>
        /// 创建所有的表,如果已存在则不会再创建
        /// </summary>
        public static void CreateTables()
        {
            using (var tempDc = new LinqCar_RentalDataContext(dbConnectionString))
            {
                var tables = tempDc.Mapping.GetTables();
                foreach (var metaTable in tables)
                {
                    try
                    {
                        //var metaTable = tempDc.Mapping.GetTable(linqTableClass);
                        //反射的方法创建对象
                        var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
                        var type = typeof(DataContext).Assembly.GetType(typeName);

                        //反射调用私有的GetCreateTableCommand 方法。
                        var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
                        var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });

                        var sqlAsString = sql.ToString();
                        tempDc.ExecuteCommand(sqlAsString);
                    }
                    catch (SqlException sqlex)
                    {
                        if (sqlex.Number == 2714)
                        {
                            throw new Exception("这个表已存在,不需要再创建");
                        }
                        else
                        {
                            throw;
                        }
                    }

                }
            }
        }

    }
}
